import { copyFileSync, existsSync, statSync, unlinkSync } from 'fs';
import { readFileSync } from 'fs-extra';
import { basename, extname, join } from 'path';
let {execSync} = require("child_process");

module.exports = Editor.Panel.define({
    listeners: {
        show() { console.log('show'); },
        hide() { console.log('hide'); },
    },
    template: readFileSync(join(__dirname, '../../../static/template/default/index.html'), 'utf-8'),
    style: readFileSync(join(__dirname, '../../../static/style/default/index.css'), 'utf-8'),
    $: {
        bg: '#bg',
        app: '#app',
        desc: '#desc',
        desc_detail: '#desc_detail',
        features: '#features',
        features_box: '#features_box',
        feature_li_1: '#feature_li_1',
        feature_li_2: '#feature_li_2',
        feature_li_3: '#feature_li_3',
        feature_li_4: '#feature_li_4',
        use: '#use',
        use_desc: '#use_desc',
        use_input: '#use_input',
        comfirm: '#comfirm',
        // check: '#check',
        footer : '#footer',
    },
    methods: {
        // 常量路径
        _tmpPngPath() { return join(__dirname, '../../../tmp.png');},
        _tmpJpgPath() { return join(__dirname, '../../../tmp.jpg');},
        _tmpJpegPath() { return join(__dirname, '../../../tmp.jpeg');},
        _tmpPngFs8Path() { return join(__dirname, '../../../tmp-fs8.png');},
        _tmpJpgFs8Path() { return join(__dirname, '../../../tmp-fs8.jpg');},
        _tmpJpegFs8Path() { return join(__dirname, '../../../tmp-fs8.jpeg');},

        hello() { },
        checkPath() { },  
        onCheck()  { },
        // 判断当前文件是否存在
        _hadFile(path:string) { return readFileSync(path, 'utf-8') != null; },
        _delete(path : string) { unlinkSync(path); },
        // 获取input组件的value，其实可以直接取，不过这边方便就进行封装
        _getInputValue(obj : HTMLElement) { return (<HTMLInputElement><any>obj).value;},
        // 设置文本
        _setText(obj:HTMLElement,str : string) { if (obj)  obj.innerHTML = str;  },
        // 查找失败
        _unfind() { this._showErr(Editor.I18n.t("texture-compator.search_failure")); },
        // 非指定资源格式
        _unPointer() { this._showErr(Editor.I18n.t("texture-compator.not_picture_format")); },
        // 更换按钮为红色
        _showErr( text :string )
        {
            this.$.comfirm!.innerHTML = text;
            this.$.comfirm?.setAttribute("class","comfirm1");
        },
        // 更换按钮为绿色
        _showLog( text :string )
        {
            this.$.comfirm!.innerHTML = text;
            this.$.comfirm?.setAttribute("class","comfirm2");
        },
        // 获取文件名并截取格式
        _getBaseNameTail(path : string)
        {
            let _basename = basename(path);
            let _split = _basename.split('.');
            let _tail = _split[_split.length - 1];
            return _tail;
        },
        // 判断当前路径是否指定格式
        _isPng(path : string) { return this._getBaseNameTail(path) == 'png'; },
        _isJpg(path : string) { return this._getBaseNameTail(path) == 'jpg' || this._getBaseNameTail(path) == 'jpeg'; },
        // 清指定path下缓存
        _clearCache(path : string) 
        {
            if(existsSync(path)) this._delete(path);  
        },
        // 清缓存
        _clearCacheTexture()
        {
            this._clearCache(this._tmpPngPath());
            this._clearCache(this._tmpPngFs8Path());
            this._clearCache(this._tmpJpgPath());
            this._clearCache(this._tmpJpgFs8Path());
            this._clearCache(this._tmpJpegPath());
            this._clearCache(this._tmpJpegFs8Path());
        },
        // 根据path获取
        // { tmpFilename : string , tmpFs8FileName : string }
        _getFilesName(path:string)
        {
            let __extname = extname(path);
            let __newFileName = join(__dirname, '../../../'+"tmp"+__extname);
            let __newFileFs8Name = join(__dirname, '../../../'+"tmp-fs8"+__extname);
            return {tmpFileName : __newFileName,tmpFs8FileName : __newFileFs8Name};
        },
        // 复制一份文件
        _copyNewFile(path:string)
        {
            let __extname = extname(path);
            let __newFileName = join(__dirname, '../../../'+"tmp"+__extname);
            copyFileSync(path,__newFileName);
            return __newFileName;
        },
        // 获取目标路径的图片，并生成一张缓存在当前目录下
        // 缓存了之后便对对应的缓存进行pngquant压缩
        _cachePathTexture(path:string)
        {
            let __newFileName = this._copyNewFile(path);
            execSync('chcp 65001 ');
            let __exePath = join(__dirname, '../../../pngquant.exe');
            execSync(__exePath + " "+ __newFileName);
        },
        // 根据环境校验文件大小
        // return {fileSize:nnnnnn byte ,fs8Size:nnnnnn byte ,precent : 50%}
        _compareBothTexture(path:string)
        {
            let __obj = this._getFilesName(path);
            let __tmpFileStat = statSync(__obj.tmpFileName) ;
            let __tmpFs8FileStat = statSync(__obj.tmpFs8FileName);
            return {fileSize : __tmpFileStat.size,fs8Size:__tmpFs8FileStat,precent : (__tmpFs8FileStat.size / __tmpFileStat.size * 100 ).toFixed(2)};
        },
        // 对path下的图片进行读取和压缩
        _onCompress(path : string)
        {
            this._clearCacheTexture();
            this._cachePathTexture(path);
            let _compareData = this._compareBothTexture(path);
            if(_compareData)
            {
                this._showLog(_compareData.precent + Editor.I18n.t("texture-compator.comfirm"));
            }
        },
        // 替换原来的目录，达到目的。
        // 并清楚
        _onReplace(path:string)
        {
            let __obj = this._getFilesName(path);
            copyFileSync(__obj.tmpFs8FileName,path);
            this._clearCacheTexture();
            this.$.use_input!.innerHTML = "";
            (<HTMLInputElement>this.$.use_input)!.value = "";
            this._showLog(Editor.I18n.t("texture-compator.replace_success"));
            this.$.comfirm!.onclick = null;
        },
        // 输入框文本变动逻辑
        // 文本变动时获取文件下的信息
        onInputUpdate() 
        {
            let p = this._getInputValue(this.$.use_input!);
            // 判断格式
            // 非指定格式则不进行压缩处理
            if(this._isJpg(p) == false && this._isPng(p) == false)
            {
                this._unPointer();
                return;
            }
            // 查找文件，避免找不到文件而报错阻塞
            if(this._hadFile(p))
            {
                this._onCompress(p);
                this.$.comfirm!.onclick = this._onReplace.bind(this,p);
            }
            else this._unfind();
        },
    },
    ready() 
    {
        this._setText(this.$.app!, Editor.I18n.t("texture-compator.pngquant"));
        this._setText(this.$.desc!,Editor.I18n.t("texture-compator.pngquant_info"));
        this._setText(this.$.desc_detail!,Editor.I18n.t("texture-compator.pngquant_info_detail"));
        this._setText(this.$.features!,Editor.I18n.t("texture-compator.features"));
        this._setText(this.$.feature_li_1!,Editor.I18n.t("texture-compator.features1"));
        this._setText(this.$.feature_li_2!,Editor.I18n.t("texture-compator.features2"));
        this._setText(this.$.feature_li_3!,Editor.I18n.t("texture-compator.features3"));
        this._setText(this.$.feature_li_4!,Editor.I18n.t("texture-compator.features4"));
        this._setText(this.$.use!,Editor.I18n.t("texture-compator.use"));
        this._setText(this.$.use_desc!,Editor.I18n.t("texture-compator.use_procedure"));
        this._showErr(Editor.I18n.t("texture-compator.not_picture"));
        this._setText(this.$.footer!,Editor.I18n.t("texture-compator.footer") );
        if(this.$.use_input)
        {
            this.$.use_input.setAttribute("placeholder",Editor.I18n.t("texture-compator.placeholder"))
            let i : HTMLInputElement = <any>this.$.use_input;
            i.addEventListener("input",this.onInputUpdate.bind(this));
        }
        if(this.$.comfirm && this.$.use_input)
        {
            this.$.comfirm.onclick = null;
        }
    },
    beforeClose() { },
    close() 
    { 
        this._clearCacheTexture();
    },
});
